package com.iqilu.ksd.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.IdentityBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.ImageSize;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.ImageUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;

import id.zelory.compressor.Compressor;
import okhttp3.Response;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/10/18.
 */

public class AuthActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private static final String TAG = "AuthActivity";

    private LigDialog ligDialog;

    private String picPath, newPicPath;
    private int status; // 0未认证 1认证界面 2认证正在审核中 3成功提交认证信息

    private ImageView btLeft;
    private TextView tvTitle;
    private ImageView imgAuth;
    private Button btSubmit;
    private Button btFinish;
    private SimpleDraweeView imgId;
    private EditText etName;
    private EditText etId;
    private RelativeLayout layInfo;

    private static final int PER_CAMERA = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        tvTitle.setText(getString(R.string.auth_title));
        tvTitle.setVisibility(View.VISIBLE);
        hideAll();
        new LoadData().execute();
    }

    private void initView(){
        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        imgAuth = getView(R.id.img_auth);
        btSubmit = getView(R.id.bt_submit);
        btFinish = getView(R.id.bt_finish);
        imgId = getView(R.id.img_id);
        etName = getView(R.id.et_name);
        etId = getView(R.id.et_id);
        layInfo = getView(R.id.lay_info);

        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toSubmit();
            }
        });
        imgId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
            }
        });
    }

    @AfterPermissionGranted(PER_CAMERA)
    private void takePhoto() {
        String perm = Manifest.permission.CAMERA;
        if (EasyPermissions.hasPermissions(this,perm)) {
            showTip();
        } else {
            EasyPermissions.requestPermissions(this,getString(R.string.per_con_camera),PER_CAMERA,perm);
        }
    }

    private void toSubmit() {
        switch (status) {
            case 1:
                goAuth();
                break;
            case 2:
                status = 1;
                break;
            case 3:
                status = 1;
                break;
            default:
                status = 1;
                break;
        }
        initUI();
    }

    private void initUI() {
        hideAll();
        switch (status) {
            case 1:
                layInfo.setVisibility(View.VISIBLE);
                btSubmit.setText(getString(R.string.auth_submit));
                break;
            case 2:
                imgAuth.setImageResource(R.drawable.bg_live_authing);
                imgAuth.setVisibility(View.VISIBLE);
                btSubmit.setText(getString(R.string.auth_edit));
                btFinish.setVisibility(View.GONE);
                btSubmit.setVisibility(View.GONE);
                break;
            case 3:
                imgAuth.setImageResource(R.drawable.bg_live_auth_submit);
                imgAuth.setVisibility(View.VISIBLE);
                btSubmit.setText(getString(R.string.auth_edit));
                btFinish.setText(getString(R.string.auth_bt_home));
                btFinish.setVisibility(View.VISIBLE);
                btSubmit.setVisibility(View.VISIBLE);
                break;
            default:
                imgAuth.setImageResource(R.drawable.bg_live_not_auth);
                imgAuth.setVisibility(View.VISIBLE);
                btSubmit.setText(getString(R.string.auth_go));
                break;
        }
        if (status != 2) {
            btSubmit.setVisibility(View.VISIBLE);
        }
    }

    private void hideAll() {
        layInfo.setVisibility(View.GONE);
        imgAuth.setVisibility(View.GONE);
        btFinish.setVisibility(View.GONE);
        btSubmit.setVisibility(View.GONE);

    }

    private void goAuth() {
        String name, idcode;
        name = etName.getText().toString();
        idcode = etId.getText().toString();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, R.string.auth_name_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(idcode)) {
            Toast.makeText(this, R.string.auth_id_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(picPath)) {
            Toast.makeText(this, R.string.auth_pic_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        new AuthThread(name, idcode).execute();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.per_con_camera))
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(requestCode)
                    .build()
                    .show();
        }
    }

    class LoadData extends AsyncTask<Void, Void, Void> {

        int code = -1;
        IdentityBean result = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ligDialog = new LigDialog(AuthActivity.this, getString(R.string.waiting));
            ligDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            String url = Api.URL_IDENTITY;
            Response response = null;
            try {
                response = OkHttpUtils.get().url(url).tag(this).build().execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    result = JSONUtils.requestDetail(response.body().string(), "data", IdentityBean.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (result != null) {
                code = result.getVerify();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ligDialog.dismiss();
            Log.i(TAG, "code=" + code);
            switch (code) {
                case 0: //等待验证
                    status = 2;
                    break;
                default: //未验证
                    status = 0;
                    break;
            }
            initUI();
        }

    }

    class AuthThread extends AsyncTask<Void, Void, Void> {

        String name, idcode;
        int result = 0;

        public AuthThread(String name, String idcode) {
            this.name = name;
            this.idcode = idcode;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ligDialog = new LigDialog(AuthActivity.this, getString(R.string.waiting));
            ligDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            Response response = null;
            String url = Api.URL_IDENTITY;
            File file = new File(picPath);
            Log.i(TAG,"AuthThread picPath="+picPath);
            try {
                response = OkHttpUtils.post().url(url).addParams("name", "" + name).addParams("idcode", "" + idcode).addFile("filedata", "" + file.getName(), file).tag(this).build().execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    result = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ligDialog.dismiss();
            if (result == 1) {
                status = 3;
                initUI();
            } else {
                Toast.makeText(AuthActivity.this, R.string.auth_submit_error, Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void showTip() {
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.popu_auth_tip);
        Button btEnsure = (Button) window.findViewById(R.id.bt_ensure);
        btEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (TextUtils.isEmpty(picPath)) {
                    picPath = newPicPath = CacheUtils.getCacheDir(AuthActivity.this) + System.currentTimeMillis() + ".jpg";
                } else {
                    newPicPath = CacheUtils.getCacheDir(AuthActivity.this) + System.currentTimeMillis() + ".jpg";
                }
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(newPicPath)));
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(intent, 0);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            picPath = newPicPath;
//          imgId.setImageURI(Uri.parse("file://" + picPath));
            new CompressThread().execute();
        }
    }

    class CompressThread extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ligDialog = new LigDialog(AuthActivity.this, getString(R.string.waiting));
            ligDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            File compressedImage = new Compressor.Builder(AuthActivity.this)
                    .setMaxWidth(ImageSize.BIG_WIDTH)
                    .setMaxHeight(ImageSize.BIG_HEIGHT)
                    .setQuality(90)
                    .setCompressFormat(Bitmap.CompressFormat.JPEG)
                    .setDestinationDirectoryPath(CacheUtils.getCompressDir(AuthActivity.this))
                    .build()
                    .compressToFile(new File(picPath));
            picPath = compressedImage.getPath();
            compressedImage = null;
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ligDialog.dismiss();
            imgId.setImageURI(Uri.parse("file://" + picPath));
        }
    }
}